<?php

namespace W3;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 开启框架模块
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Menu extends Widget
{
    /**
     * 当前菜单
     *
     * @access public
     * @var integer
     */
    public $index;
	
    /**
     * 当前菜单标题
     * @var string
     */
    public $title;
    
    /**
     * 当前项目链接
     * @var string
     */
    public $currentUrl;
	
    /**
     * 当前增加项目链接
     * @var string
     */
    public $addLink;

    public function execute() 
	{
        $this->parameter([
		
		    # 父节点数据
		    'parentNodes'=>[],
			
			# 子节点数据
		    'childNodes'=> []
		], true);
		
		extract($this->parameter->many('baseUrl', 'parentNodes', 'childNodes', 'widget'));

		# 按优先级对操作排序
        $parentNodes = Util::arrayMultiSort($parentNodes, 'priority');

		$menu = [];
		$defaultChildeNode = [NULL, NULL, NULL, 'admin', false, NULL];
		$currentUrl = rtrim($this->request->url(true), '/');
        $currentUrlParts = parse_url($currentUrl);
        $currentUrlParams = [];
        if (!empty($currentUrlParts['query'])) {
            parse_str($currentUrlParts['query'], $currentUrlParams);
        }

		$currentUrlParts['path'] = rtrim($currentUrlParts['path'], '/');

        foreach ($parentNodes as $key => $parentNode) 
		{
            if (!$parentNode || !isset($childNodes[$key])) {
                continue;
            }

            $children = [];
            $showedChildrenCount = 0;
			$firstUrl = NULL;
			
			$menu[$key]['name'] = $parentNode['name'];

            foreach ($childNodes[$key] as $childNode) 
			{
				$childNode += $defaultChildeNode;
				list ($name, $title, $url, $access, $hidden, $addLink) = $childNode;
				
                // 保存最原始的hidden信息
                $orgHidden = $hidden;
				
                if (NULL !== $access && !$this->auth->check($access, true)) {
                    continue;
                }

                // compare url
                $urlParts = parse_url(rtrim($url, '/'));
                $urlParams = [];
                if (!empty($urlParts['query'])) {
                    parse_str($urlParts['query'], $urlParams);
                }

                $validate = true;

                if ($urlParts['path'] != $currentUrlParts['path']) {
                    $validate = false;
                } else {
                    foreach ($urlParams as $paramName => $paramValue) 
					{
                        if (!isset($currentUrlParams[$paramName])) {
                            $validate = false;
                            break;
                        }
                    }
                }
                
                if ($hidden && $validate) {
                    $hidden = false;
                }

                if (!$hidden) {

                    $showedChildrenCount ++;

                    if (NULL == $firstUrl) {
						$firstUrl = $url;
                    }
					
                    if (NULL === $name) {
                        $name = $widget->parameter->title;
                    }
                    
                    if (NULL === $title) {
                        $title = $widget->parameter->title;
                    }
					
                    if (NULL === $addLink) {
                        $addLink = $widget->parameter->addLink;
                    }
                }

                if ($validate) {
                    $this->index = $key;
					$this->title = $title;
                    $widget->parameter(['title' => $title]);
					$this->addLink = $addLink ? $addLink : NULL;
                }
				
                !$hidden && $children[] = [
				    'current' => $validate,
                    'name' => $name,
                    'title' => $title,
                    'url' => $validate ? $currentUrl : $url,
					'access' => $access,
					'hidden' => $hidden,
					'addLink' => $addLink,
					'orgHidden' => $orgHidden,
					'icon'=>base_convert(sprintf("%u", crc32($key . '-' . $name)), 10, 36)
                ];
            }

			if($showedChildrenCount) {
				
			    $menu[$key] += [
			        'current'=>$key === $this->index, 
				    'count'=>$showedChildrenCount, 
				    'parent'=>1,
				    'icon'=>$parentNode['icon'],
				    'child'=>$children, 
			    ];
			} else {
				$menu[$key] = null;
				unset($menu[$key]);
			}
        }
    
        $this->currentUrl = $currentUrl;
		
		$this->stack = $menu;		
    }

}
